package com.bachongLightNovel.message.service.impl;

import com.bachongLightNovel.error.ErrorCodeEnum;
import com.bachongLightNovel.exception.CustomException;
import com.bachongLightNovel.message.mapper.MessageMapper;
import com.bachongLightNovel.message.service.MessageService;
import com.bachongLightNovel.model.pojo.message.Message;
import com.bachongLightNovel.model.vo.message.MessageVo;
import com.bachongLightNovel.utils.UserInfoUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * @author vermouth
 */
@Service
public class MessageServiceImpl implements MessageService {

    @Autowired
    private MessageMapper messageMapper;

    /**
     * 获取当前登录用户的消息列表
     * @return Result
     */
    @Override
    public List<MessageVo> getCurrentMessages() {
        //获取当前登录用户的id
        Long userId = UserInfoUtil.getUser().getId();
        //根据id查询当前登录用户的消息集合,按照时间进行排序
        List<Message> list=messageMapper.selectByTargetId(userId);
        //封装对应属性
        List<MessageVo> voList=new ArrayList<>();
        for (Message message : list) {
            MessageVo vo = new MessageVo();
            BeanUtils.copyProperties(message,vo);
            voList.add(vo);
        }
        return voList;
    }

    /**
     * 根据id删除此条消息
     * @param id :
     * @return Result
     */
    @Override
    public void removeMessageById(Long id) {
        //判断当前消息是否所属当前用户
        //获取当前登录用户id
        Long userId = UserInfoUtil.getUser().getId();
        Message message=messageMapper.selectById(id);
        if (message ==null || !userId.equals(message.getTargetId())){
            throw new CustomException(ErrorCodeEnum.UNKNOW_ERROR);
        }
        //在数据库中删除响应消息
        messageMapper.deleteById(id);
    }

    /**
     * 向用户发送消息
     * @param message :
     * @return Result
     */
    @Override
    public void sendMessage(Message message) {
        //补全相应属性
            //获取当前用户id
        Long fromId = UserInfoUtil.getUser().getId();
        message.setFromId(fromId);
        message.setCreateTime(LocalDateTime.now());
        message.setIsRead((short)0);
        message.setType((short)0);
        //插入到数据库当中
        messageMapper.insert(message);
    }
}
